<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.2.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/myblog/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/myblog/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/myblog/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/myblog/images/logo.svg" color="#222">

<link rel="stylesheet" href="/myblog/css/main.css">



<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.1/css/all.min.css">
  <link rel="stylesheet" href="//cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css">

<script class="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"kuang-yudi.gitee.io","root":"/myblog/","images":"/myblog/images","scheme":"Gemini","version":"8.1.0","exturl":false,"sidebar":{"position":"right","display":"post","padding":18,"offset":12},"copycode":false,"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":"gitalk","storage":true,"lazyload":false,"nav":null,"activeClass":"gitalk"},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/myblog/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false}};
  </script>
<meta name="description" content="Promise原理">
<meta property="og:type" content="article">
<meta property="og:title" content="js设计模式">
<meta property="og:url" content="http://kuang-yudi.gitee.io/myblog/2021/01/22/js%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/index.html">
<meta property="og:site_name" content="KY迪的个人博客">
<meta property="og:description" content="Promise原理">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2021-01-22T08:33:41.000Z">
<meta property="article:modified_time" content="2021-03-04T04:49:16.387Z">
<meta property="article:author" content="匡宇迪">
<meta property="article:tag" content="js设计模式">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="http://kuang-yudi.gitee.io/myblog/2021/01/22/js%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/">


<script class="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>
<title>js设计模式 | KY迪的个人博客</title>
  



  <noscript>
  <style>
  body { margin-top: 2rem; }

  .use-motion .menu-item,
  .use-motion .sidebar,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header {
    visibility: visible;
  }

  .use-motion .header,
  .use-motion .site-brand-container .toggle,
  .use-motion .footer { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle,
  .use-motion .custom-logo-image {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line {
    transform: scaleX(1);
  }

  .search-pop-overlay, .sidebar-nav { display: none; }
  .sidebar-panel { display: block; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/myblog/" class="brand" rel="start">
      <i class="logo-line"></i>
      <h1 class="site-title">KY迪的个人博客</h1>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">个人技术博客</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu">
        <li class="menu-item menu-item-home"><a href="/myblog/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li>
        <li class="menu-item menu-item-tags"><a href="/myblog/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a></li>
        <li class="menu-item menu-item-categories"><a href="/myblog/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a></li>
        <li class="menu-item menu-item-archives"><a href="/myblog/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</div>
        
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <section class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%AE%9A%E4%B9%89"><span class="nav-number">1.</span> <span class="nav-text">定义</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%88%9B%E5%BB%BA%E5%9E%8B%E6%A8%A1%E5%BC%8F"><span class="nav-number">2.</span> <span class="nav-text">创建型模式</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%8D%95%E4%BE%8B%E6%A8%A1%E5%BC%8F"><span class="nav-number">2.1.</span> <span class="nav-text">单例模式</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E7%90%86%E8%A7%A3"><span class="nav-number">2.1.1.</span> <span class="nav-text">理解</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%BA%94%E7%94%A8"><span class="nav-number">2.1.2.</span> <span class="nav-text">应用</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%A0%B8%E5%BF%83%E4%BB%A3%E7%A0%81%E5%AE%9E%E7%8E%B0"><span class="nav-number">2.1.3.</span> <span class="nav-text">核心代码实现</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%80%BB%E7%BB%93"><span class="nav-number">2.1.4.</span> <span class="nav-text">总结</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%B7%A5%E5%8E%82%E6%A8%A1%E5%BC%8F"><span class="nav-number">2.2.</span> <span class="nav-text">工厂模式</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E7%9B%AE%E7%9A%84"><span class="nav-number">2.2.1.</span> <span class="nav-text">目的</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%88%86%E7%B1%BB"><span class="nav-number">2.2.2.</span> <span class="nav-text">分类</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%BA%94%E7%94%A8-1"><span class="nav-number">2.2.3.</span> <span class="nav-text">应用</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%8E%9F%E5%9E%8B%E6%A8%A1%E5%BC%8F"><span class="nav-number">2.3.</span> <span class="nav-text">原型模式</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E7%BB%93%E6%9E%84%E5%9E%8B%E6%A8%A1%E5%BC%8F"><span class="nav-number">3.</span> <span class="nav-text">结构型模式</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E9%80%82%E9%85%8D%E5%99%A8%E6%A8%A1%E5%BC%8F"><span class="nav-number">3.1.</span> <span class="nav-text">适配器模式</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%BB%A3%E7%90%86%E6%A8%A1%E5%BC%8F"><span class="nav-number">3.2.</span> <span class="nav-text">代理模式</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%BA%94%E7%94%A8-2"><span class="nav-number">3.2.1.</span> <span class="nav-text">应用</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%9B%BE%E7%89%87%E6%87%92%E5%8A%A0%E8%BD%BD"><span class="nav-number">3.2.1.1.</span> <span class="nav-text">图片懒加载</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%90%88%E5%B9%B6-http-%E8%AF%B7%E6%B1%82%E2%80%94%E2%80%94%E4%BE%8B%EF%BC%9A%E5%90%8C%E6%AD%A5%E6%95%B0%E6%8D%AE"><span class="nav-number">3.2.1.2.</span> <span class="nav-text">合并 http 请求——例：同步数据</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E7%BC%93%E5%AD%98%E4%BB%A3%E7%90%86"><span class="nav-number">3.2.1.3.</span> <span class="nav-text">缓存代理</span></a></li></ol></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E8%A1%8C%E4%B8%BA%E5%9E%8B%E6%A8%A1%E5%BC%8F"><span class="nav-number">4.</span> <span class="nav-text">行为型模式</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E8%A7%82%E5%AF%9F%E8%80%85%E6%A8%A1%E5%BC%8F-%E5%8F%91%E5%B8%83%E8%AE%A2%E9%98%85%E6%A8%A1%E5%BC%8F"><span class="nav-number">4.1.</span> <span class="nav-text">观察者模式(发布订阅模式)</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E7%AD%96%E7%95%A5%E6%A8%A1%E5%BC%8F"><span class="nav-number">4.2.</span> <span class="nav-text">策略模式</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E8%BF%AD%E4%BB%A3%E5%99%A8%E6%A8%A1%E5%BC%8F"><span class="nav-number">4.3.</span> <span class="nav-text">迭代器模式</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%BD%9C%E7%94%A8"><span class="nav-number">4.3.1.</span> <span class="nav-text">作用</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%BB%A3%E7%A0%81"><span class="nav-number">4.3.2.</span> <span class="nav-text">代码</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%91%BD%E4%BB%A4%E6%A8%A1%E5%BC%8F"><span class="nav-number">4.4.</span> <span class="nav-text">命令模式</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%BB%A3%E7%A0%81%E5%AE%9E%E7%8E%B0"><span class="nav-number">4.4.1.</span> <span class="nav-text">代码实现</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E7%8A%B6%E6%80%81%E6%A8%A1%E5%BC%8F"><span class="nav-number">4.5.</span> <span class="nav-text">状态模式</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%BB%A3%E7%A0%81-1"><span class="nav-number">4.5.1.</span> <span class="nav-text">代码</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E7%89%B9%E7%82%B9"><span class="nav-number">4.5.2.</span> <span class="nav-text">特点</span></a></li></ol></li></ol></li></ol></div>
        </section>
        <!--/noindex-->

        <section class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="匡宇迪"
      src="https://static.pptstore.net/picture/19/19/e1feb44f42cdf7e1202b_s.jpg">
  <p class="site-author-name" itemprop="name">匡宇迪</p>
  <div class="site-description" itemprop="description">用于记录学习web前端</div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/myblog/archives/">
        
          <span class="site-state-item-count">38</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/myblog/categories/">
          
        <span class="site-state-item-count">7</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/myblog/tags/">
          
        <span class="site-state-item-count">87</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author site-overview-item animated">
      <span class="links-of-author-item">
        <a href="https://github.com/tonykyd/tonykyd.github.io" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;tonykyd&#x2F;tonykyd.github.io" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:1303665509@qq.com" title="E-Mail → mailto:1303665509@qq.com" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>



        </section>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://kuang-yudi.gitee.io/myblog/2021/01/22/js%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="https://static.pptstore.net/picture/19/19/e1feb44f42cdf7e1202b_s.jpg">
      <meta itemprop="name" content="匡宇迪">
      <meta itemprop="description" content="用于记录学习web前端">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="KY迪的个人博客">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          js设计模式
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2021-01-22 16:33:41" itemprop="dateCreated datePublished" datetime="2021-01-22T16:33:41+08:00">2021-01-22</time>
    </span>
      <span class="post-meta-item">
        <span class="post-meta-item-icon">
          <i class="far fa-calendar-check"></i>
        </span>
        <span class="post-meta-item-text">更新于</span>
        <time title="修改时间：2021-03-04 12:49:16" itemprop="dateModified" datetime="2021-03-04T12:49:16+08:00">2021-03-04</time>
      </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/myblog/categories/%E9%9D%A2%E8%AF%95%E9%A2%98/" itemprop="url" rel="index"><span itemprop="name">面试题</span></a>
        </span>
    </span>

  
    <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="far fa-eye"></i>
      </span>
      <span class="post-meta-item-text">阅读次数：</span>
      <span id="busuanzi_value_page_pv"></span>
    </span>
</div>

            <div class="post-description">Promise原理</div>
        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <h1 id="定义"><a href="#定义" class="headerlink" title="定义"></a>定义</h1><p>针对特定问题的简洁而优雅的解决方案</p>
<h1 id="创建型模式"><a href="#创建型模式" class="headerlink" title="创建型模式"></a>创建型模式</h1><h2 id="单例模式"><a href="#单例模式" class="headerlink" title="单例模式"></a>单例模式</h2><h3 id="理解"><a href="#理解" class="headerlink" title="理解"></a>理解</h3><p>一个构造函数只能有一个实例</p>
<p>提高代码复用性，减少代码量，减少内存消耗(只创建一个实例)</p>
<h3 id="应用"><a href="#应用" class="headerlink" title="应用"></a>应用</h3><p>自定义弹出层 —— 每次显示都是同一个 div<br>一般用于全局缓存，比如全局 window，唯一登录浮窗等</p>
<p><strong>特点：</strong></p>
<ol>
<li>需要频繁的进行创建和销毁的对象</li>
<li>创建对象时耗时过多或耗费资源过多，但又经常用到的对象；</li>
<li>工具类对象或者频繁访问数据库或文件的对象。</li>
</ol>
<p>单例模式应用的场景一般发现在以下条件下：</p>
<p>（1）资源共享的情况下，避免由于资源操作时导致的性能或损耗等。</p>
<p>（2）控制资源的情况下，方便资源之间的互相通信。如线程池等。</p>
<h3 id="核心代码实现"><a href="#核心代码实现" class="headerlink" title="核心代码实现"></a>核心代码实现</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F; 单例模式——一个构造函数只有一个实例</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; 闭包储存构造函数和实例</span><br><span class="line">const Person &#x3D; (function () &#123;</span><br><span class="line">  &#x2F;&#x2F; 构造函数</span><br><span class="line">  function Person(name, age, sex) &#123;</span><br><span class="line">    this.name &#x3D; name</span><br><span class="line">    this.age &#x3D; age</span><br><span class="line">    this.sex &#x3D; sex</span><br><span class="line">  &#125;</span><br><span class="line">  Person.prototype.say &#x3D; function () &#123;</span><br><span class="line">    console.log(&#96;我叫$&#123;this.name&#125;,年龄是$&#123;this.age&#125;,性别$&#123;this.sex&#125;&#96;);</span><br><span class="line">  &#125;</span><br><span class="line">  &#x2F;&#x2F; instance用于作实例的载体</span><br><span class="line">  let instance &#x3D; null</span><br><span class="line"></span><br><span class="line">  &#x2F;&#x2F; 返回函数形成闭包</span><br><span class="line">  return function (...args) &#123;</span><br><span class="line">    &#x2F;&#x2F; instance不存在时赋值一个实例</span><br><span class="line">    &#x2F;&#x2F; instance存在时返回的是之前的实例</span><br><span class="line">    if (!instance) instance &#x3D; new Person(...args)</span><br><span class="line">    return instance</span><br><span class="line">  &#125;</span><br><span class="line">&#125;)()</span><br><span class="line"></span><br><span class="line">const p1 &#x3D; Person(&#39;张三&#39;, 28, &#39;男&#39;)</span><br><span class="line">const p2 &#x3D; Person() &#x2F;&#x2F; 赋值</span><br><span class="line">console.log(p1);</span><br><span class="line">console.log(p2);</span><br><span class="line">console.log(p1 &#x3D;&#x3D;&#x3D; p2);</span><br><span class="line">p1.say()</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h3><p>只需要实例化一次，后续每次实例化都是拿到第一次实例化的对象</p>
<h2 id="工厂模式"><a href="#工厂模式" class="headerlink" title="工厂模式"></a>工厂模式</h2><p>工厂模式是创建对象的常用设计模式，本质上是一个负责生产对象实例的工厂。</p>
<h3 id="目的"><a href="#目的" class="headerlink" title="目的"></a>目的</h3><p>不暴露创建对象的具体逻辑，将创建对象的逻辑封装在一个函数中，这个函数就称为一个工厂。</p>
<h3 id="分类"><a href="#分类" class="headerlink" title="分类"></a>分类</h3><p>简单工厂，工厂方法和抽象工厂。</p>
<p>抽象工厂方法的实现</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F;安全模式创建的工厂方法函数</span><br><span class="line">let UserFactory &#x3D; function(role) &#123;</span><br><span class="line">  if(this instanceof UserFactory) &#123;</span><br><span class="line">    var s &#x3D; new this[role]();</span><br><span class="line">    return s;</span><br><span class="line">  &#125; else &#123;</span><br><span class="line">    return new UserFactory(role);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F;工厂方法函数的原型中设置所有对象的构造函数</span><br><span class="line">UserFactory.prototype &#x3D; &#123;</span><br><span class="line">  SuperAdmin: function() &#123;</span><br><span class="line">    this.name &#x3D; &quot;超级管理员&quot;,</span><br><span class="line">    this.viewPage &#x3D; [&#39;首页&#39;, &#39;通讯录&#39;, &#39;发现页&#39;, &#39;应用数据&#39;, &#39;权限管理&#39;]</span><br><span class="line">  &#125;,</span><br><span class="line">  Admin: function() &#123;</span><br><span class="line">    this.name &#x3D; &quot;管理员&quot;,</span><br><span class="line">    this.viewPage &#x3D; [&#39;首页&#39;, &#39;通讯录&#39;, &#39;发现页&#39;, &#39;应用数据&#39;]</span><br><span class="line">  &#125;,</span><br><span class="line">  NormalUser: function() &#123;</span><br><span class="line">    this.name &#x3D; &#39;普通用户&#39;,</span><br><span class="line">    this.viewPage &#x3D; [&#39;首页&#39;, &#39;通讯录&#39;, &#39;发现页&#39;]</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F;调用</span><br><span class="line">let superAdmin &#x3D; UserFactory(&#39;SuperAdmin&#39;);</span><br><span class="line">let admin &#x3D; UserFactory(&#39;Admin&#39;)</span><br><span class="line">let normalUser &#x3D; UserFactory(&#39;NormalUser&#39;)</span><br></pre></td></tr></table></figure>

<h3 id="应用-1"><a href="#应用-1" class="headerlink" title="应用"></a>应用</h3><p>通常用于根据权限生成角色(实例)的场景</p>
<h2 id="原型模式"><a href="#原型模式" class="headerlink" title="原型模式"></a>原型模式</h2><p>用原型实例指定创建对象的种类，并且通过拷贝这些原型创建新的对象。</p>
<p>定义好原型对象，通过 Object,create 方法将原型对象指定为新对象的原型</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">var prototype &#x3D; &#123;</span><br><span class="line">    name: &#39;Jack&#39;,</span><br><span class="line">    getName: function() &#123;</span><br><span class="line">        return this.name</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">var obj &#x3D; Object.create(prototype, &#123;</span><br><span class="line">    job: &#123;</span><br><span class="line">        value: &#39;IT&#39;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">console.log(obj.getName())  &#x2F;&#x2F; Jack</span><br><span class="line">console.log(obj.job)  &#x2F;&#x2F; IT</span><br><span class="line">console.log(obj.__proto__ &#x3D;&#x3D;&#x3D; prototype)  &#x2F;&#x2F;true</span><br></pre></td></tr></table></figure>

<h1 id="结构型模式"><a href="#结构型模式" class="headerlink" title="结构型模式"></a>结构型模式</h1><h2 id="适配器模式"><a href="#适配器模式" class="headerlink" title="适配器模式"></a>适配器模式</h2><p>解决两个接口间不匹配的问题，不会改变原有的接口，而是由一个对象对另一个对象的包装。</p>
<p>谷歌地图类中是 show 方法渲染地图<br>百度地图类中是 display 方法渲染地图<br>通过适配器类对百度地图进行封装(同样通过 show 方法间接调用 display 渲染)</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line">class GooleMap &#123;</span><br><span class="line">    show() &#123;</span><br><span class="line">        console.log(&#39;渲染谷歌地图&#39;)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">class BaiduMap &#123;</span><br><span class="line">    display() &#123;</span><br><span class="line">        console.log(&#39;渲染百度地图&#39;)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; 定义适配器类, 对BaiduMap类进行封装</span><br><span class="line">class BaiduMapAdapter &#123;</span><br><span class="line">    show() &#123;</span><br><span class="line">        var baiduMap &#x3D; new BaiduMap()</span><br><span class="line">        return baiduMap.display()</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">function render(map) &#123;</span><br><span class="line">    if (map.show instanceof Function) &#123;</span><br><span class="line">        map.show()</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">render(new GooleMap())         &#x2F;&#x2F; 渲染谷歌地图</span><br><span class="line">render(new BaiduMapAdapter())  &#x2F;&#x2F; 渲染百度地图</span><br></pre></td></tr></table></figure>

<h2 id="代理模式"><a href="#代理模式" class="headerlink" title="代理模式"></a>代理模式</h2><p>为其他对象提供一种代理，也就是当其他对象直接访问该对象时，如果开销较大，就可以通过这个代理层控制对该对象的访问。</p>
<p>理解：在代理方法中调用原方法，这样就可以调用原方法前进行操作：</p>
<ul>
<li>图片懒加载——调用前先给一个提示加载的图片路径，加载完成后再更改为正式图片</li>
<li>合并 http 请求——调用前将数据缓存起来，设定定时器发送数据(调用发送数据的方法)，清空数据。</li>
<li>缓存代理——调用前将数据缓存起来，判断两次传入参数是否一样，是则用缓存数据，否则调用计算数据的方法(原方法)</li>
</ul>
<h3 id="应用-2"><a href="#应用-2" class="headerlink" title="应用"></a>应用</h3><p>常见的使用场景为懒加载，合并 http 请求(同步数据)，缓存代理。</p>
<h4 id="图片懒加载"><a href="#图片懒加载" class="headerlink" title="图片懒加载"></a>图片懒加载</h4><p>图片真正加载完之前，使用一张 loading 占位图片，等图片真正加载完再给图片设置 src 属性</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line">var addImg &#x3D; (function()&#123;</span><br><span class="line">    var img &#x3D; document.createElement(&#39;img&#39;);</span><br><span class="line">    document.body.appendChild(img);</span><br><span class="line">    return &#123;</span><br><span class="line">        setSrc: function(src)&#123;</span><br><span class="line">            img.src &#x3D; src;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;)();</span><br><span class="line">var proxyAddImg &#x3D; (function()&#123; &#x2F;&#x2F;图片预加载虚拟代理函数</span><br><span class="line">    var img &#x3D; new Image(); &#x2F;&#x2F;创建“灯塔”</span><br><span class="line">    img.onload &#x3D; function()&#123;</span><br><span class="line">        addImg(this.src); &#x2F;&#x2F;一旦图片加载完毕，立刻显示</span><br><span class="line">    &#125;</span><br><span class="line">    return &#123; &#x2F;&#x2F;改</span><br><span class="line">        setSrc: function(src)&#123;</span><br><span class="line">            addImg.setSrc(&#39;loading.gif&#39;); &#x2F;&#x2F;先添加占位图片</span><br><span class="line">            img.src &#x3D; src; &#x2F;&#x2F; 加载图片</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;)();</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">proxyAddImg(&#39;demo.png&#39;);</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h4 id="合并-http-请求——例：同步数据"><a href="#合并-http-请求——例：同步数据" class="headerlink" title="合并 http 请求——例：同步数据"></a>合并 http 请求——例：同步数据</h4><p>两秒内选中的 input 一次性提交</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">function synData(ID)&#123;</span><br><span class="line">    console.log(ID +　&#39;正在同步到服务器...&#39;);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">var proxySynData &#x3D; (function()&#123;</span><br><span class="line">    var cache &#x3D; &#123;&#125;, &#x2F;&#x2F;用对象作为缓存载体</span><br><span class="line">        timer;      &#x2F;&#x2F;定时器</span><br><span class="line">    return function(ID)&#123;</span><br><span class="line">        if(!timer)&#123;</span><br><span class="line">            timer &#x3D; setTimeout(function()&#123;</span><br><span class="line">                synData(Object.keys(cache).join()); &#x2F;&#x2F;同步合并后的数据</span><br><span class="line">                cache &#x3D; &#123;&#125;; &#x2F;&#x2F;清空缓存</span><br><span class="line">                clearTimeout(timer);&#x2F;&#x2F;清除定时器</span><br><span class="line">                timer &#x3D; null;&#x2F;&#x2F;方便垃圾回收</span><br><span class="line">            &#125;, 2000);</span><br><span class="line">        &#125;</span><br><span class="line">        cache[ID] &#x3D; 1; &#x2F;&#x2F;把数据作为对象的属性存储(避免重复)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;)();</span><br><span class="line"></span><br><span class="line">var list &#x3D; document.getElementsByTagName(&#39;input&#39;);</span><br><span class="line">for(let i &#x3D; 0 ; i &lt; list.length ; i++)&#123;</span><br><span class="line">    list[i].onclick &#x3D; function()&#123;</span><br><span class="line">        if(this.checked)&#123;</span><br><span class="line">            proxySynData(this.id);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="缓存代理"><a href="#缓存代理" class="headerlink" title="缓存代理"></a>缓存代理</h4><p>缓存一些开销很大的运算结果<br>如果第二次执行函数的时候，传递了同样的参数，那么就直接使用缓存的结果</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">var add &#x3D; function()&#123;</span><br><span class="line">    var sum &#x3D; 0;</span><br><span class="line">    for(var i &#x3D; 0; i &lt; arguments.length; i++)&#123;</span><br><span class="line">        sum +&#x3D; arguments[i];</span><br><span class="line">    &#125;</span><br><span class="line">    return sum;</span><br><span class="line">&#125;;</span><br><span class="line">var proxyAdd &#x3D; (function()&#123;</span><br><span class="line">    var cache &#x3D; &#123;&#125;; &#x2F;&#x2F;缓存运算结果的缓存对象</span><br><span class="line">    return function()&#123;</span><br><span class="line">        var args &#x3D; Array.prototype.join.call(arguments);&#x2F;&#x2F;把参数用逗号组成一个字符串作为“键”</span><br><span class="line">        &#x2F;&#x2F; 如果对象cache中有此数据的键，使用缓存的值</span><br><span class="line">        if(cache.hasOwnProperty(args))&#123;&#x2F;&#x2F;等价 args in cache</span><br><span class="line">            console.log(&#39;使用缓存结果&#39;);</span><br><span class="line">            return cache[args];&#x2F;&#x2F;直接使用缓存对象的“值”</span><br><span class="line">        &#125;</span><br><span class="line">        console.log(&#39;计算结果&#39;);</span><br><span class="line">        return cache[args] &#x3D; add.apply(this,arguments);&#x2F;&#x2F;使用本体函数计算结果并加入缓存</span><br><span class="line">    &#125;</span><br><span class="line">&#125;)();</span><br><span class="line">console.log(proxyAdd(1,2,3,4,5)); &#x2F;&#x2F;15</span><br><span class="line">console.log(proxyAdd(1,2,3,4,5)); &#x2F;&#x2F;15</span><br><span class="line">console.log(proxyAdd(1,2,3,4,5)); &#x2F;&#x2F;15</span><br></pre></td></tr></table></figure>

<h1 id="行为型模式"><a href="#行为型模式" class="headerlink" title="行为型模式"></a>行为型模式</h1><h2 id="观察者模式-发布订阅模式"><a href="#观察者模式-发布订阅模式" class="headerlink" title="观察者模式(发布订阅模式)"></a>观察者模式(发布订阅模式)</h2><p>监控被观察者状态，一旦状态改变，触发观察者的方法</p>
<p>订阅：存储状态对应的观察者的方法<br>发布：状态改变触发对应存储的方法</p>
<h2 id="策略模式"><a href="#策略模式" class="headerlink" title="策略模式"></a>策略模式</h2><p>将算法的使用与算法的实现分离开来。适用于有多个判断分支的场景，如解决表单验证的问题。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F; 对于vip客户</span><br><span class="line">function vipPrice() &#123;</span><br><span class="line">    this.discount &#x3D; 0.5;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">vipPrice.prototype.getPrice &#x3D; function(price) &#123;</span><br><span class="line">　　return price * this.discount;</span><br><span class="line">&#125;</span><br><span class="line">&#x2F;&#x2F; 对于老客户</span><br><span class="line">function oldPrice() &#123;</span><br><span class="line">    this.discount &#x3D; 0.3;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">oldPrice.prototype.getPrice &#x3D; function(price) &#123;</span><br><span class="line">    return price * this.discount;</span><br><span class="line">&#125;</span><br><span class="line">&#x2F;&#x2F; 对于普通客户</span><br><span class="line">function Price() &#123;</span><br><span class="line">    this.discount &#x3D; 1;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">Price.prototype.getPrice &#x3D; function(price) &#123;</span><br><span class="line">    return price ;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; 上下文，对于客户端的使用</span><br><span class="line">function Context() &#123;</span><br><span class="line">    this.name &#x3D; &#39;&#39;;</span><br><span class="line">    this.strategy &#x3D; null;</span><br><span class="line">    this.price &#x3D; 0;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">Context.prototype.set &#x3D; function(name, strategy, price) &#123;</span><br><span class="line">    this.name &#x3D; name;</span><br><span class="line">    this.strategy &#x3D; strategy;</span><br><span class="line">    this.price &#x3D; price;</span><br><span class="line">&#125;</span><br><span class="line">Context.prototype.getResult &#x3D; function() &#123;</span><br><span class="line">    console.log(this.name + &#39; 的结账价为: &#39; + this.strategy.getPrice(this.price));</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">var context &#x3D; new Context();</span><br><span class="line">var vip &#x3D; new vipPrice();</span><br><span class="line">context.set (&#39;vip客户&#39;, vip, 200);</span><br><span class="line">context.getResult();   &#x2F;&#x2F; vip客户 的结账价为: 100</span><br><span class="line"></span><br><span class="line">var old &#x3D; new oldPrice();</span><br><span class="line">context.set (&#39;老客户&#39;, old, 200);</span><br><span class="line">context.getResult();  &#x2F;&#x2F; 老客户 的结账价为: 60</span><br><span class="line"></span><br><span class="line">var Price &#x3D; new Price();</span><br><span class="line">context.set (&#39;普通客户&#39;, Price, 200);</span><br><span class="line">context.getResult();  &#x2F;&#x2F; 普通客户 的结账价为: 200</span><br></pre></td></tr></table></figure>

<h2 id="迭代器模式"><a href="#迭代器模式" class="headerlink" title="迭代器模式"></a>迭代器模式</h2><p>定义一个方法顺序访问一个对象中的元素，而且不需要暴露该对象的内部表示。</p>
<h3 id="作用"><a href="#作用" class="headerlink" title="作用"></a>作用</h3><p>把迭代的过程从业务逻辑中分离出来，不用关心对象内部构造，也可以顺序访问内部元素</p>
<h3 id="代码"><a href="#代码" class="headerlink" title="代码"></a>代码</h3><p>迭代器模式使目标对象和迭代器对象分离，符合开放封闭原则</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line">class Creater &#123;</span><br><span class="line">    constructor(list) &#123;</span><br><span class="line">        this.list &#x3D; list</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    &#x2F;&#x2F; 创建一个迭代器，也叫遍历器</span><br><span class="line">    createIterator() &#123;</span><br><span class="line">        return new Iterator(this)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">class Iterator &#123;</span><br><span class="line">    constructor(creater) &#123;</span><br><span class="line">        this.list &#x3D; creater.list</span><br><span class="line">        this.index &#x3D; 0</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    &#x2F;&#x2F; 判断是否遍历完数据</span><br><span class="line">    isDone() &#123;</span><br><span class="line">        if (this.index &gt;&#x3D; this.list.length) &#123;</span><br><span class="line">            return true</span><br><span class="line">        &#125;</span><br><span class="line">        return false</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    next() &#123;</span><br><span class="line">        return this.list[this.index++]</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">var arr &#x3D; [1, 2, 3, 4]</span><br><span class="line"></span><br><span class="line">var creater &#x3D; new Creater(arr)</span><br><span class="line">var iterator &#x3D; creater.createIterator()</span><br><span class="line">console.log(iterator.list)  &#x2F;&#x2F; [1, 2, 3, 4]</span><br><span class="line">while (!iterator.isDone()) &#123;</span><br><span class="line">    console.log(iterator.next())</span><br><span class="line">    &#x2F;&#x2F; 1</span><br><span class="line">    &#x2F;&#x2F; 2</span><br><span class="line">    &#x2F;&#x2F; 3</span><br><span class="line">    &#x2F;&#x2F; 4</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="命令模式"><a href="#命令模式" class="headerlink" title="命令模式"></a>命令模式</h2><p>命令的发布者和接收者之间，定义一个命令对象，命令对象暴露出一个统一的接口给命令的发布者，而命令的发布者不用去管接收者是如何执行命令的，做到命令发布者和接收者的解耦。</p>
<h3 id="代码实现"><a href="#代码实现" class="headerlink" title="代码实现"></a>代码实现</h3><p>给不同按钮添加不同功能：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br></pre></td><td class="code"><pre><span class="line">&lt;body&gt;</span><br><span class="line">  &lt;div&gt;</span><br><span class="line">    &lt;button id&#x3D;&quot;btn1&quot;&gt;按钮1&lt;&#x2F;button&gt;</span><br><span class="line">    &lt;button id&#x3D;&quot;btn2&quot;&gt;按钮2&lt;&#x2F;button&gt;</span><br><span class="line">    &lt;button id&#x3D;&quot;btn3&quot;&gt;按钮3&lt;&#x2F;button&gt;</span><br><span class="line">  &lt;&#x2F;div&gt;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">  &lt;script&gt;</span><br><span class="line">    var btn1 &#x3D; document.getElementById(&#39;btn1&#39;)</span><br><span class="line">    var btn2 &#x3D; document.getElementById(&#39;btn2&#39;)</span><br><span class="line">    var btn3 &#x3D; document.getElementById(&#39;btn3&#39;)</span><br><span class="line"></span><br><span class="line">    &#x2F;&#x2F; 定义一个命令发布者(执行者)的类</span><br><span class="line">    class Executor &#123;</span><br><span class="line">      setCommand(btn, command) &#123;</span><br><span class="line">        btn.onclick &#x3D; function () &#123;</span><br><span class="line">          command.execute()</span><br><span class="line">        &#125;</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    &#x2F;&#x2F; 定义一个命令接收者</span><br><span class="line">    class Menu &#123;</span><br><span class="line">      refresh() &#123;</span><br><span class="line">        console.log(&#39;刷新菜单&#39;)</span><br><span class="line">      &#125;</span><br><span class="line"></span><br><span class="line">      addSubMenu() &#123;</span><br><span class="line">        console.log(&#39;增加子菜单&#39;)</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    &#x2F;&#x2F; 定义一个刷新菜单的命令对象的类</span><br><span class="line">    class RefreshMenu &#123;</span><br><span class="line">      constructor(receiver) &#123;</span><br><span class="line">        &#x2F;&#x2F; 命令对象与接收者关联</span><br><span class="line">        this.receiver &#x3D; receiver</span><br><span class="line">      &#125;</span><br><span class="line"></span><br><span class="line">      &#x2F;&#x2F; 暴露出统一的接口给命令发布者Executor</span><br><span class="line">      execute() &#123;</span><br><span class="line">        this.receiver.refresh()</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    &#x2F;&#x2F; 定义一个增加子菜单的命令对象的类</span><br><span class="line">    class AddSubMenu &#123;</span><br><span class="line">      constructor(receiver) &#123;</span><br><span class="line">        &#x2F;&#x2F; 命令对象与接收者关联</span><br><span class="line">        this.receiver &#x3D; receiver</span><br><span class="line">      &#125;</span><br><span class="line">      &#x2F;&#x2F; 暴露出统一的接口给命令发布者Executor</span><br><span class="line">      execute() &#123;</span><br><span class="line">        this.receiver.addSubMenu()</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    var menu &#x3D; new Menu() &#x2F;&#x2F; 命令接收者对象</span><br><span class="line">    var executor &#x3D; new Executor() &#x2F;&#x2F; 命令执行者对象</span><br><span class="line"></span><br><span class="line">    &#x2F;&#x2F; 命令接收者作为参数传入RefreshMenu，则refreshMenu中的execute方法内this.receiver.refresh()变成menu.refresh()</span><br><span class="line">    var refreshMenu &#x3D; new RefreshMenu(menu)</span><br><span class="line"></span><br><span class="line">    &#x2F;&#x2F; 给按钮1添加刷新功能,执行menu.refresh()</span><br><span class="line">    executor.setCommand(btn1, refreshMenu)</span><br><span class="line"></span><br><span class="line">    &#x2F;&#x2F; 命令接收者作为参数传入AddSubMenu，则addSubMenu中的execute方法内this.receiver.addSubMenu()变成menu.addSubMenu()</span><br><span class="line">    var addSubMenu &#x3D; new AddSubMenu(menu)</span><br><span class="line"></span><br><span class="line">    &#x2F;&#x2F; 给按钮2添加增加子菜单功能,执行menu.addSubMenu()</span><br><span class="line">    executor.setCommand(btn2, addSubMenu)</span><br><span class="line"></span><br><span class="line">        &#x2F;&#x2F; 如果想给按钮3增加删除菜单的功能，就继续增加删除菜单的命令对象和接收者的具体删除方法，而不必修改命令对象</span><br><span class="line">  &lt;&#x2F;script&gt;</span><br><span class="line">&lt;&#x2F;body&gt;</span><br></pre></td></tr></table></figure>

<h2 id="状态模式"><a href="#状态模式" class="headerlink" title="状态模式"></a>状态模式</h2><p>当一个对象的内在状态改变时允许改变其行为，这个对象看起来像是改变了其类。</p>
<h3 id="代码-1"><a href="#代码-1" class="headerlink" title="代码"></a>代码</h3><p>每次点击，在弱光、强光、关闭状态下切换</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br></pre></td><td class="code"><pre><span class="line">&lt;button id&#x3D;&quot;btn&quot;&gt;123&lt;&#x2F;button&gt;</span><br><span class="line">&lt;script&gt;</span><br><span class="line">  &#x2F;&#x2F; 定义一个关闭状态的类</span><br><span class="line">  class OffLightState &#123;</span><br><span class="line">    constructor(light) &#123;</span><br><span class="line">      this.light &#x3D; light</span><br><span class="line">    &#125;</span><br><span class="line">    &#x2F;&#x2F; 每个类都需要这个方法，在不同状态下按都需要触发这个方法</span><br><span class="line">    pressBtn() &#123;</span><br><span class="line">      this.light.setState(this.light.weekLightState)</span><br><span class="line">      console.log(&#39;开启弱光&#39;)</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  &#x2F;&#x2F; 定义一个弱光状态的类</span><br><span class="line">  class WeekLightState &#123;</span><br><span class="line">    constructor(light) &#123;</span><br><span class="line">      this.light &#x3D; light</span><br><span class="line">    &#125;</span><br><span class="line">    pressBtn() &#123;</span><br><span class="line">      this.light.setState(this.light.strongLightState)</span><br><span class="line">      console.log(&#39;开启强光&#39;)</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  &#x2F;&#x2F; 定义一个强光状态的类</span><br><span class="line">  class StrongLightState &#123;</span><br><span class="line">    constructor(light) &#123;</span><br><span class="line">      this.light &#x3D; light</span><br><span class="line">    &#125;</span><br><span class="line">    pressBtn() &#123;</span><br><span class="line">      this.light.setState(this.light.offLightState)</span><br><span class="line">      console.log(&#39;关闭电灯&#39;)</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  &#x2F;&#x2F; 定义一个类，每个状态类都是它的属性，通过属性调用状态中的方法</span><br><span class="line">  &#x2F;&#x2F; 同时每个状态类中挂载这个类的实例来调用此类的方法</span><br><span class="line">  class Light &#123;</span><br><span class="line">    constructor() &#123;</span><br><span class="line">      this.offLightState &#x3D; new OffLightState(this)</span><br><span class="line">      this.weekLightState &#x3D; new WeekLightState(this)</span><br><span class="line">      this.strongLightState &#x3D; new StrongLightState(this)</span><br><span class="line">      this.currentState &#x3D; null</span><br><span class="line">    &#125;</span><br><span class="line">    setState(newState) &#123;</span><br><span class="line">      this.currentState &#x3D; newState</span><br><span class="line">    &#125;</span><br><span class="line">    init() &#123;</span><br><span class="line">      this.currentState &#x3D; this.offLightState</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  let light &#x3D; new Light()</span><br><span class="line">  light.init()</span><br><span class="line">  var btn &#x3D; document.getElementById(&#39;btn&#39;)</span><br><span class="line">  btn.onclick &#x3D; function () &#123;</span><br><span class="line">    light.currentState.pressBtn()</span><br><span class="line">  &#125;</span><br><span class="line">&lt;&#x2F;script&gt;</span><br></pre></td></tr></table></figure>

<h3 id="特点"><a href="#特点" class="headerlink" title="特点"></a>特点</h3><ul>
<li><p>通过定义不同的状态类，根据状态的改变而改变对象的行为。</p>
</li>
<li><p>不必把大量的逻辑都写在被操作对象的类中，而且容易增加新的状态</p>
</li>
</ul>

    </div>

    
    
    

    <footer class="post-footer">
          <div class="followme">
  <span>欢迎关注我的其它发布渠道</span>

  <div class="social-list">

      <div class="social-item">
        <a target="_blank" class="social-link" href="/myblog/images/wechat_channel.jpg">
          <span class="icon">
            <i class="fab fa-weixin"></i>
          </span>

          <span class="label">WeChat</span>
        </a>
      </div>
  </div>
</div>

          <div class="post-tags">
              <a href="/myblog/tags/js%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/" rel="tag"># js设计模式</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/myblog/2021/01/22/%E8%99%9A%E6%8B%9Fdom/" rel="prev" title="虚拟dom">
                  <i class="fa fa-chevron-left"></i> 虚拟dom
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/myblog/2021/02/23/ui%E4%BD%9C%E5%93%81/" rel="next" title="ui作品">
                  ui作品 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






    <div class="comments" id="gitalk-container"></div>

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      const activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      const commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>
</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">匡宇迪</span>
</div>
<div class="busuanzi-count">
    <span class="post-meta-item" id="busuanzi_container_site_uv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-item" id="busuanzi_container_site_pv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>

    </div>
  </footer>

  
  <script src="//cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js"></script>
<script src="/myblog/js/utils.js"></script><script src="/myblog/js/motion.js"></script><script src="/myblog/js/next-boot.js"></script>

  
<script src="/myblog/js/local-search.js"></script>






  
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>






<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/gitalk@1.7.0/dist/gitalk.css">

<script>
NexT.utils.loadComments('#gitalk-container', () => {
  NexT.utils.getScript('//cdn.jsdelivr.net/npm/gitalk@1.7.0/dist/gitalk.min.js', () => {
    var gitalk = new Gitalk({
      clientID    : '1926f8a1c453a1121d8d',
      clientSecret: '426722f9eef7599f8ebb3220379e704ea007a5f2',
      repo        : '',
      owner       : '',
      admin       : [''],
      id          : 'c38d8f95b4a78b73fa82ed3c6e60cd22',
        language: '',
      distractionFreeMode: true
    });
    gitalk.render('gitalk-container');
  }, window.Gitalk);
});
</script>

</body>
</html>
